<script setup>
import { ref, onMounted, watch, computed } from 'vue';

const props = defineProps({
  animationType: {
    type: String,
    default: 'fadeIn'
  },
  animationDuration: {
    type: Number,
    default: 1
  },
  animationDelay: {
    type: Number,
    default: 0
  },
  triggerOffset: {
    type: Number,
    default: 0.5,
    validator: value => value >= 0 && value <= 1
  },
  isAnimated: {
    type: Boolean,
    default: false
  },
  once: {
    type: Boolean,
    default: true
  },
  targetSelector: {
    type: String,
    default: null
  }
});

const emit = defineEmits(['animation-start', 'animation-end', 'update:isAnimated']);

const element = ref(null);
const observer = ref(null);
const internalIsAnimated = ref(props.isAnimated);

const animationStyle = computed(() => ({
  animationDuration: `${props.animationDuration}s`,
  animationDelay: `${props.animationDelay}s`,
  animationFillMode: 'both'
}));

const handleAnimationStart = () => {
  emit('animation-start');
  emit('update:isAnimated', true);
};

const handleAnimationEnd = () => {
  emit('animation-end');
  if (props.once && observer.value) {
    observer.value.disconnect();
  }
};

const initObserver = () => {
  const options = {
    threshold: props.triggerOffset,
    rootMargin: '0px'
  };

  observer.value = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting && !internalIsAnimated.value) {
        internalIsAnimated.value = true;
        handleAnimationStart();
      }
    });
  }, options);

  const target = props.targetSelector ?
      element.value.querySelector(props.targetSelector) :
      element.value;

  if (target) {
    observer.value.observe(target);
  }
};

watch(() => props.isAnimated, (newVal) => {
  internalIsAnimated.value = newVal;
  if (!newVal) initObserver();
});

onMounted(() => {
  initObserver();
});
</script>

<template>
  <div
      ref="element"
      :class="['scroll-animation', `animate-${animationType}`]"
      :style="animationStyle"
      @animationend="handleAnimationEnd"
  >
    <slot />
  </div>
</template>

<style scoped>
.scroll-animation {
  opacity: 0;
}

.animate-fadeIn {
  animation-name: fadeIn;
}

.animate-slideInLeft {
  animation-name: slideInLeft;
}

.animate-slideInRight {
  animation-name: slideInRight;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-100%);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(100%);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}
</style>